package com.seis_645.appTesting;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class SalesPersonDataSource {

	// database fields
	private SQLiteDatabase database;
	private MySQLiteHelper db_helper;
	private String[] all_columns = { MySQLiteHelper.SLP_ID,
			MySQLiteHelper.SLP_DLR_ID, MySQLiteHelper.SLP_FNAME,
			MySQLiteHelper.SLP_LNAME };

	public SalesPersonDataSource(Context context) {
		this.db_helper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = db_helper.getWritableDatabase();
	}

	public void close() {
		db_helper.close();
	}

	public Salesperson create_salesperson(int dealer_id, String fname,
			String lname) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.SLP_DLR_ID, dealer_id);
		values.put(MySQLiteHelper.SLP_FNAME, fname);
		values.put(MySQLiteHelper.SLP_LNAME, lname);

		long insert_id = this.database.insert(MySQLiteHelper.TBL_SALESPERSON,
				null, values);
		Cursor cursor = this.database.query(MySQLiteHelper.TBL_SALESPERSON,
				this.all_columns, MySQLiteHelper.SLP_ID + " = " + insert_id,
				null, null, null, null);
		cursor.moveToFirst();
		Salesperson sales_person = cursor_to_salesperson(cursor);
		cursor.close();

		return sales_person;
	}

	public void delete(Salesperson salesperson) {
		long id = salesperson.get_id();
		System.out.println("Comment deleted with id: " + id);
	}

	public List<Salesperson> get_all_salespeople() {
		List<Salesperson> people = new ArrayList<Salesperson>();

		Cursor cursor = this.database.query(MySQLiteHelper.TBL_SALESPERSON,
				all_columns, null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Salesperson slp = cursor_to_salesperson(cursor);
			people.add(slp);
			cursor.moveToNext();
		}

		cursor.close();
		return people;
	}

	private Salesperson cursor_to_salesperson(Cursor cursor) {
		Salesperson slp = new Salesperson(cursor.getLong(1), cursor.getString(2), cursor.getString(3));
		slp.set_id(cursor.getLong(0));
		return slp;
	}

}
